package com.yl.chainStore.services.impl

import com.yl.chainStore.services.IFileUploadService
import com.yl.chainStore.services.warehouse.IWarehouseService
import com.yl.chainStore.util.DcmToImageUtil
import com.yl.common.ErrorCode
import com.yl.common.control.ResponseBody
import com.yl.common.control.returnError
import com.yl.common.control.returnSuccess
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.stereotype.Service
import org.springframework.web.multipart.MultipartFile
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import javax.servlet.http.HttpServletRequest

/**
 * @description :文件上传实现层
 * @author :吴枫
 * @create :2021-07-06 13:54:00
 */
@Service
class FileUploadServiceImpl : IFileUploadService {

    companion object {
        private val log = LoggerFactory.getLogger(IWarehouseService::class.java)
    }

    //绝对路径
    @Value("\${config.file-save-path}")
    private lateinit var resources: String

    //相对路径
    @Value("\${config.resources-rootPath}")
    private val resourcesRootPath: String? = null

    override fun uploadFile(fileUpload: MultipartFile, req: HttpServletRequest): ResponseBody {
            val df = SimpleDateFormat("yyyy-MM").format(Date())
        val dir = File(resources + df)
        if (!dir.exists()) {
            dir.mkdirs()
        }
        // 文件名
        var fileName = fileUpload.originalFilename ?: return returnError(ErrorCode.FILENAME_EMPTY)
        //后缀名
        val suffixName = fileName.substring(fileName.lastIndexOf("."))
        fileName = UUID.randomUUID().toString() + suffixName

        val newFile = File(resources + df + File.separator + fileName)
        log.info("文件上传，保存位置:{}", newFile.absoluteFile)
        //指定本地文件夹存储图片
        return try {
            //报错图片到新建的文件夹
            fileUpload.transferTo(newFile)
            var imgUrl = req.scheme.toString() + "://" + req.serverName +  resourcesRootPath + df + File.separator + fileName
            var localPath=resourcesRootPath + df + File.separator + fileName
            log.info("返回上传文件地址:{}", imgUrl)
            val map= mutableMapOf<String,String>()
            if (".dcm" == suffixName) {
                val dcmFilePath: String = resources + df + File.separator + fileName
                val dcmToImageUtil=DcmToImageUtil()
                dcmToImageUtil.create2(dcmFilePath)
                imgUrl = "$imgUrl.jpg"
                localPath="$localPath.jpg"
            }
            map["url"] = imgUrl
            map["localPath"] = localPath
            return returnSuccess(map)
        } catch (e: Exception) {
            log.error("上传失败:{}", e.printStackTrace())
            returnError(ErrorCode.FAIL_TO_UPLOAD_IMAGE)
        }
    }


}
